package com.xiangyang.pos.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.xiangyang.pos.R;
import com.xiangyang.pos.bean.AdvDataBean;
import com.xiangyang.pos.bean.ApkDataBean;
import com.xiangyang.pos.constant.AppConstant;
import com.xiangyang.pos.http.HttpClient;
import com.xiangyang.pos.http.RequestParameters;
import com.xiangyang.pos.logger.Logger;
import com.xiangyang.pos.upgrade.DownloadService;
import com.xiangyang.pos.utils.SharedUtils;

import org.greenrobot.eventbus.EventBus;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/16 0016.
 *
 * 首页
 *
 * @author YeDalin
 *
 */

public class FirstActivity extends Activity {

    private CircleImageView ivPhoto;
    private ImageView ivScan;

    private TextView tvOrderList;
    private TextView tvGetOrderList;

    private LinearLayout myDialog;
    private ImageView ivDialog;
    private TextView tvDialog;

    private ImageView image;

    private DownloadService.DownloadBinder downloadBinder;
    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            downloadBinder = (DownloadService.DownloadBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        initView();
        setMyClick();
        getHttp();
        setApk();
    }

    private void initView(){
        ivPhoto=findViewById(R.id.iv_photo);
        ivScan=findViewById(R.id.iv_scan);

        tvOrderList=findViewById(R.id.tv_order_list);
        tvGetOrderList=findViewById(R.id.tv_get_order_list);

        myDialog=findViewById(R.id.my_dialog);
        ivDialog=findViewById(R.id.iv_dialog);
        tvDialog=findViewById(R.id.tv_dialog);

        image=findViewById(R.id.image);

    }

    private void setMyClick(){
        ivPhoto.setOnClickListener(listener);
        ivScan.setOnClickListener(listener);
        tvOrderList.setOnClickListener(listener);
        tvGetOrderList.setOnClickListener(listener);
    }

    private View.OnClickListener listener=new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.iv_photo:
                    isOtherAccount();
                    break;
                case R.id.iv_scan:
                    Intent intent=new Intent(FirstActivity.this,OrderDetailsActivity.class);
                    startActivity(intent);
                    break;
                case R.id.tv_order_list:
                    Intent intent1=new Intent(FirstActivity.this,OrderListActivity.class);
                    startActivity(intent1);
                    break;
                case R.id.tv_get_order_list:
                    Intent intent2=new Intent(FirstActivity.this,GetOrderListActivity.class);
                    startActivity(intent2);
                    break;
            }
        }
    };


    /*
    * 是否切换其他账号
    * */
    private void isOtherAccount(){

        final AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("是否切换账号");
        builder.setNegativeButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent=new Intent(FirstActivity.this,EmployeeLoginActivity.class);
                startActivity(intent);
                finish();
            }
        });

        builder.setPositiveButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                builder.setCancelable(true);
            }
        });

        builder.show();
    }


    /*
    * 退出程序
    * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            final AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setCancelable(false);
            builder.setTitle("是否退出程序");
            builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    System.exit(0);
                }
            });
            builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    builder.setCancelable(true);
                }
            });
            builder.show();
        }

        return super.onKeyDown(keyCode, event);
    }


//    链接消息网络
    private void getHttp(){

        String UserTOKEN = SharedUtils.getStringPrefs(this, "UserTOKEN", "");
        final String DIALOG_URL= AppConstant.POS_URL+"/Adv/An/getAdv"+"/u="+UserTOKEN;


        Logger.e("xxxx",DIALOG_URL);

        HttpClient httpClient=new HttpClient();
        httpClient.post(DIALOG_URL, null, new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {

                Logger.e("xxxadv",result);

                if(!result.equals("Error")){

                    Gson gson=new Gson();
                    AdvDataBean bean=gson.fromJson(result,AdvDataBean.class);
                    if(bean!=null){
                        if(bean.getStatus()==1){
                            if(bean.getData().getContent()!=null){
                                image.setVisibility(View.VISIBLE);

                                try {

                                    String str=bean.getData().getContent().substring(0,bean.getData().getContent().lastIndexOf("|"));
                                    Logger.e("xxxx",str);
                                    Picasso.with(FirstActivity.this)
                                            .load(AppConstant.PHOTO_URL+ str)
                                            .into(image);

                                }catch (RuntimeException e){

                                }



//                                tvDialog.setText(Html.fromHtml(bean.getData().getContent()).toString());

                                if(bean.getData().getJump().equals("1")){
                                    setAdvUrl(bean.getData().getUrl());
                                }

                            }

                        }
                    }
                }else {
                    Toast.makeText(FirstActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

//    跳转WebActivity,并传网址
    private void setAdvUrl(final String url){
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(FirstActivity.this,WebActivity.class);
                intent.putExtra("url",url);
                startActivity(intent);
            }
        });
    }


    private RequestParameters apkData(){
        RequestParameters parameters=new RequestParameters();
        parameters.put("version","1");
        return parameters;
    }
//    链接apk更新网络
    private void setApk(){
        String UserTOKEN = SharedUtils.getStringPrefs(this, "UserTOKEN", "");
        final String APK_URL= AppConstant.POS_URL+"/Version/An/getVersion"+"/u="+UserTOKEN;


        HttpClient httpClient=new HttpClient();
        httpClient.post(APK_URL, apkData(), new HttpClient.OnResponseListener() {
            @Override
            public void onResponse(String result) {
                if(!result.equals("Error")){

                    Logger.e("xxxx",result);

                    Gson gson=new Gson();
                    ApkDataBean bean=gson.fromJson(result,ApkDataBean.class);
                    if(bean!=null){
                        if(bean.getStatus()==1){
                            if(bean.getData().getNumber()>1.0){
                                setApkDialog(bean.getData().getDownload());
                            }
                        }
                    }

                }else {
                    Toast.makeText(FirstActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

//    apk更新对话框
    private void setApkDialog(final String download){
        final AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("发现新版本，是否更新？");
        builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                builder.setCancelable(true);
            }
        });
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                Intent intent = new Intent(FirstActivity.this, DownloadService.class);
                startService(intent);
                bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (downloadBinder != null) {
                            downloadBinder.startDownload(download);
                        }
                    }
                }, 1000);

            }
        });
        builder.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (downloadBinder!=null){
            unbindService(serviceConnection);
        }
    }

}
